#!/usr/bin/env node
var net = require('net'),
    socks = require('./socks.js');

// Create server
// The server accepts SOCKS connections. This particular server acts as a proxy.
var HOST='127.0.0.1',
    PORT='8888',
    server = socks.createServer(function(socket, port, address, proxy_ready) {

      // Implement your own proxy here! Do encryption, tunnelling, whatever! Go flippin' mental!
      // I plan to tunnel everything including SSH over an HTTP tunnel. For now, though, here is the plain proxy:

      console.log('Got through the first part of the SOCKS protocol.')
      var proxy = net.createConnection(port, address, proxy_ready);

      proxy.on('data', function(d) {
        try {
          console.log('receiving ' + d.length + ' bytes from proxy');
          socket.write(d);
        } catch(err) {
        }
      });
      socket.on('data', function(d) {
        // If the application tries to send data before the proxy is ready, then that is it's own problem.
        try {
          console.log('sending ' + d.length + ' bytes to proxy');
          proxy.write(d);
        } catch(err) {
        }
      });

      proxy.on('close', function(had_error) {
        socket.end();
        console.error('The proxy closed');
      }.bind(this));
      socket.on('close', function(had_error) {
        if (this.proxy !== undefined) {
          proxy.removeAllListeners('data');
          proxy.end();
        }
        console.error('The application closed');
      }.bind(this));

    });

server.on('error', function (e) {
    console.error('SERVER ERROR: %j', e);
    if (e.code == 'EADDRINUSE') {
        console.log('Address in use, retrying in 10 seconds...');
        setTimeout(function () {
            console.log('Reconnecting to %s:%s', HOST, PORT);
            server.close();
            server.listen(PORT, HOST);
        }, 10000);
    }
});
server.listen(PORT, HOST);

// vim: set filetype=javascript syntax=javascript :
